package gupiaodown;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

public class DownAndAnalyzeGupiaoFromSina {

	public int n_downhttpcode = 200;
	public String m_msg = "";
	public DownAndAnalyzeGupiaoFromSina() {
		// TODO Auto-generated constructor stub
	}
	
	public static void main(String[] arg0)
	{
		Map map = new HashMap();
		map.put("key", "123");
		map.put("value", "12www");
		JSONObject obj = (JSONObject)map;
		String str = obj.toJSONString();
		System.out.print(str);
	}
	//输入是json格式数据 {"name":"伊利股份","code":"000123","startdate":"2017-01-03","enddata":"2017-02-5"}
	public List genDownTask(String content)
	{
		List list = new ArrayList();
		Object obj =  JSONValue.parse(content);
		if(obj != null)
		{
			String classname = obj.getClass().getName();
			if(classname.equalsIgnoreCase("net.minidev.json.JSONObject"))
			{
				list = genGuTaskOneinput((JSONObject)obj);
			}
			else if(classname.equalsIgnoreCase("net.minidev.json.JSONArray"))
			{
				JSONArray jarry = (JSONArray)obj;
				for(int i = 0; i < jarry.size(); i++)
				{
					JSONObject objone = (JSONObject) jarry.get(i);
					List listone = genGuTaskOneinput(objone);
					list.addAll(listone);
				}
			}
			else
			{}
			
		}
		
		return list;
	}
	
	private List genGuTaskOneinput(JSONObject obj)
	{
		List list = new ArrayList();
		if(obj != null)
		{
			String name = (String) obj.get("name");
			String code = (String)obj.get("code");
			String startdate = (String) obj.get("startdate");
			String enddate = (String) obj.get("enddata");
			
			String startY="";
			String endY = "";
			String startM = "";
			String endM = "";
			
			if(name != null)
			{
				if(name.isEmpty())
				{
					n_downhttpcode = -2;
					m_msg = "参数name为空字符串";
					return list;
				}
				if(code== null)
				{
					n_downhttpcode = -3;
					m_msg = "参数code为空";
					return list;
				}
				if(code.isEmpty())
				{
					n_downhttpcode = -4;
					m_msg = "参数code为空字符串";
					return list;
				}
				if(startdate != null)
				{
					if(!startdate.isEmpty())
					{
						if(enddate != null)
						{
							if(enddate.isEmpty())
							{
								//获取当前时间
								enddate = getCurrentDate();
							}
						}
						else
						{
							//获取当前时间\
							enddate = getCurrentDate();
						}
							
					}
					else
					{
						//获取当前时间 作为开始时间和结束时间，计算季度
						startdate = getCurrentDate();
						enddate = getCurrentDate();
					}
					
					//获取开始季度和结束季度
					startY = getYear(startdate);
					startM = getMonth(startdate);
					endY =  getYear(enddate);
					endM =  getMonth(enddate);
					
				}
				else
				{
					//获取当前时间
					startdate = getCurrentDate();
					enddate = getCurrentDate();

					startY = getYear(startdate);
					startM = getMonth(startdate);
					
					endY =  getYear(enddate);
					endM =  getMonth(enddate);
				}
				
				///主体
				int nstarty = Integer.parseInt(startY);
				int nendy = Integer.parseInt(endY);
				int nstartj = getJidu(startM);
				int nendj = getJidu(endM);
				int i= 0;
				for(i = nstarty; i <= nendy; i++)
				{
					int nyear = i;
					if(nyear <  nendy)
					{
						int nstart = 1;
						if(nyear == nstarty)
							nstart = nstartj;
						for(int j = nstart; j <= 4;j++)
						{
							int jidu =j;
							//下载分析
							String tmp = String.format("%d",i);
							String jtmp = String.format("%d", jidu);
							String url = formUrlHis(code,tmp,jtmp);
							Map mapone = new HashMap();
							mapone.put("code", code);
							mapone.put("name", name);
							mapone.put("url", url);
							list.add(mapone);
						}
					}
					else
					{//$year  == $yearend
						int start = 1;
						if(nyear == nstarty)
							start = nstartj;
							
						for(int j = start; j <= nendj;j++)
						{
							int jidu =j;
							String tmp = String.format("%d",i);
							String jtmp = String.format("%d", jidu);
							String url = formUrlHis(code,tmp,jtmp);
							
							Map mapone = new HashMap();
							mapone.put("code", code);
							mapone.put("name", name);
							mapone.put("url", url);
							list.add(mapone);
						}
					}
				}//for i
			}
			else
			{
				n_downhttpcode = -1;//参数 name为空
				m_msg = "参数 name为空";
			}
		}
		return list;
	}
	
	public static int getJidu(String month)
	{
		int jidu = 0;
		if(month == null)
			month="";
		if(month.isEmpty())
			return jidu;
		int yue = Integer.parseInt(month);
		if(yue>=1 && yue <= 3)
			jidu=1;
		else if(yue>=4 && yue <= 6)
			jidu=2;
		else if(yue>=7 && yue  <= 9)
			jidu=3;
		else if(yue >=10 && yue <= 12)
			jidu=4;
		else
			jidu=0;
		return jidu;
	}
	public static String getCurrentDate()
	{
		String date = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		date=df.format(new Date());// new Date()为获取当前系统时间
		
		return date;
	}
	public static String getYear(String strdate)
	{
		String strY = "";
		int nlen = strdate.length();
		if(nlen >= 4)
			strY = strdate.substring(0, 4);
		return strY;
		//int nindex = startdate.indexOf('-');
	}
	
	public static String getMonth(String strdate)
	{
		String strM = "";
		int nindex = strdate.indexOf('-');
		if(nindex >0)
		{
			int nindex1 = strdate.indexOf('-', nindex+1);
			if(nindex1 > 0)
			{
				strM = strdate.substring(nindex+1, nindex1);
			}
		}
		return strM;
	}
	
	private  String formUrlHis(String gucode,String year,String season)
	{
		String url = "http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/"+gucode+".phtml?year="+year+"&jidu="+season;
		return url;
	}
	
	
	public String  analyzePage(String url,String strPage,String code,String name)
	{
		String str = "";
		String reg= "<td class=\"tdr\"><div align=\"center\"><strong>交易金额\\(元\\)</strong></div></td>([\\s\\S]*?)</table>";
		String content = paraseOnePatternOnestr(reg,strPage);
		if(content != null)
		{
			reg = "<tr .*?>[\\s\\S]*?<td><div align=\"center\">([\\s\\S]*?)</div></td>[\\s\\S]*?<td><div align=\"center\">(.*?)</div></td>[\\s\\S]*?<td><div align=\"center\">(.*?)</div></td>[\\s\\S]*?<td><div align=\"center\">(.*?)</div></td>[\\s\\S]*?<td class=\"tdr\"><div align=\"center\">(.*?)</div></td>[\\s\\S]*?<td class=\"tdr\"><div align=\"center\">(.*?)</div></td>[\\s\\S]*?<td class=\"tdr\"><div align=\"center\">(.*?)</div></td>[\\s\\S]*?</tr>";
			List list = paraseOnePatterns(reg,content);
			JSONArray listnew = new JSONArray();
//			List listnew = new ArrayList();
			//1 jydate 时间  2 开盘价kpj  3最高价 zgj 4收盘价 spj   5最低价 zdj  6交易量jyl  7交易金额 jyje
			int nsize = list.size();
			for(int i = 0; i< nsize; i++)
			{
				Map mapone = (Map) list.get(i);
				JSONObject objnew = new JSONObject();
				String jydate = (String) mapone.get("1");
				String kpj = (String) mapone.get("2");
				String zgj = (String) mapone.get("3");
				String spj = (String)mapone.get("4");
				String zdj = (String)mapone.get("5");
				String jyl = (String)mapone.get("6");
				String jyje = (String)mapone.get("7");
				jydate = HTMLSpirit.delHTMLTag(jydate);
				objnew.put("jydate", jydate);
				objnew.put("kpj", kpj);
				objnew.put("spj", spj);
				objnew.put("zdj", zdj);
				objnew.put("zgj", zgj);
				objnew.put("jyl", jyl);
				objnew.put("jyje", jyje);
				objnew.put("code", code);
				objnew.put("name", name);
				listnew.add(objnew);
				
			}//for i
			str = listnew.toJSONString();
				
		}
			
		return str;//
	}

	public String downLoadOnePage(String url)
	{
		String strpage = "";
		int nloopcnt = 0;
		while(nloopcnt <= 3)
		{
			Connection con = Jsoup.connect(url);
			con.timeout(10*1000);
			con.header("Accept-Language", "zh-CN,zh;q=0.8");
			con.header("Connection","Keep-Alive");
			con.header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");
			con.ignoreContentType(true);
			try 
			{
				Document doc = con.get();
				Response re = con.response();
				
				int ncode = re.statusCode();
				if(ncode == 200)
				{
					strpage = re.body();
					break;
				}
				else if((ncode >=100 && ncode <200)||(ncode >= 500 && ncode < 600))
				{//重试
					nloopcnt++;
					//String strMsg = formatLogInfo("","downLoadOneContent down to try","","httpcode="+ncode,"");
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					continue;
				}
				
				n_downhttpcode = ncode; 
			}catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			nloopcnt++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}//while
		
		return strpage;
	}
	 //一条正则匹配,匹配一个结果,一个结果有一个元素
    private  static String paraseOnePatternOnestr(String strReg,String strpage)
    {
    	String strRet = "";
    	Pattern p1 = Pattern.compile(strReg);
		Matcher m1=p1.matcher(strpage);
		boolean bFind = false;
		while(m1.find())
		{
			int nCnt = m1.groupCount();
			if(nCnt > 0)
			{
				strRet= m1.group(1);
				break;
			}
		}//while
		return strRet;
    }
    
	 //一条正则匹配,匹配多组结果
    private  static List<Map> paraseOnePatterns(String reg,String Text)
    {
    	List<Map> list = new ArrayList<Map>();
    	
    	Pattern p1 = Pattern.compile(reg);
		Matcher m1=p1.matcher(Text);
		boolean bFind = false;
		while(m1.find())
		{
			int nCnt = m1.groupCount();
			if(nCnt > 0)
			{
				Map maps = new HashMap();
				
				for(int i = 1; i <= nCnt;i++)
				{
					String key = String.format("%d", i);
					String v = m1.group(i);
					maps.put(key, v);
				}//for
				list.add(maps);
			}
		}//while
    	return list;
    }
}
